{% extends 'admin/base.html' %}
{% set active_page = 'users' %}

{% block title %}用户管理{% endblock %}

{% block page_title %}用户管理{% endblock %}

{% block page_subtitle %}管理系统用户信息、权限和账户状态{% endblock %}



{% block content %}

            <div class="content-scroll">
                 <!-- 用户统计卡片 -->
                 <div class="row mb-4">
                    <div class="col-lg-3 col-md-6 mb-3">
                        <div class="metric-card">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <div class="text-primary">
                                    <i class="bi bi-people" style="font-size: 2.5rem;"></i>
                                </div>
                                <div class="text-end">
                                    <h3 class="mb-0">{{ stats.total_users }}</h3>
                                    <small class="text-muted">总用户数</small>
                                </div>
                            </div>
                            <div class="d-flex align-items-center">
                                <span class="badge bg-success me-2">+{{ stats.user_growth }}%</span>
                                <small class="text-muted">较上月增长</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-md-6 mb-3">
                        <div class="metric-card">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <div class="text-info">
                                    <i class="bi bi-person-plus" style="font-size: 2.5rem;"></i>
                                </div>
                                <div class="text-end">
                                    <h3 class="mb-0">{{ stats.new_users_today }}</h3>
                                    <small class="text-muted">今日新增</small>
                                </div>
                            </div>
                            <div class="d-flex align-items-center">
                                <span class="badge bg-info me-2">日均 {{ stats.daily_avg }}</span>
                                <small class="text-muted">新增用户</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-md-6 mb-3">
                        <div class="metric-card">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <div class="text-success">
                                    <i class="bi bi-person-check" style="font-size: 2.5rem;"></i>
                                </div>
                                <div class="text-end">
                                    <h3 class="mb-0">{{ stats.active_users }}</h3>
                                    <small class="text-muted">活跃用户</small>
                                </div>
                            </div>
                            <div class="d-flex align-items-center">
                                <span class="badge bg-success me-2">{{ stats.active_rate }}%</span>
                                <small class="text-muted">活跃率</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-md-6 mb-3">
                        <div class="metric-card">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <div class="text-warning">
                                    <i class="bi bi-star" style="font-size: 2.5rem;"></i>
                                </div>
                                <div class="text-end">
                                    <h3 class="mb-0">{{ stats.premium_users }}</h3>
                                    <small class="text-muted">付费会员</small>
                                </div>
                            </div>
                            <div class="d-flex align-items-center">
                                <span class="badge bg-warning me-2">{{ stats.premium_rate }}%</span>
                                <small class="text-muted">付费率</small>
                            </div>
                        </div>
                    </div>
                </div>
            <!-- 功能按钮栏 -->
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h4 class="mb-0">会员列表管理</h4>
                <div class="btn-group">
                    <button class="btn btn-success me-2" data-bs-toggle="modal" data-bs-target="#addUserModal">
                        <i class="bi bi-person-plus me-1"></i>添加用户
                    </button>
                    <button class="btn btn-outline-primary">
                        <i class="bi bi-download me-1"></i>导出数据
                    </button>
                </div>
            </div>

                <!-- 搜索筛选栏 -->
                <div class="search-filter-bar">
                    <div class="row align-items-center">
                        <div class="col-md-4">
                            <div class="input-group">
                                <span class="input-group-text">
                                    <i class="bi bi-search"></i>
                                </span>
                                <input type="text" class="form-control" id="searchInput" placeholder="搜索用户名、邮箱、手机号...">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <select class="form-select" id="statusFilter">
                                <option value="">全部状态</option>
                                <option value="active">正常</option>
                                <option value="inactive">已禁用</option>
                                <option value="unverified">待激活</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <select class="form-select" id="memberTypeFilter">
                                <option value="">全部类型</option>
                                <option value="basic">基础会员</option>
                                <option value="premium">高级会员</option>
                                <option value="vip">VIP会员</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <select class="form-select" id="timeFilter">
                                <option value="">注册时间</option>
                                <option value="today">今天</option>
                                <option value="week">本周</option>
                                <option value="month">本月</option>
                                <option value="year">本年</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <button class="btn btn-outline-secondary w-100" onclick="applyFilters()">
                                <i class="bi bi-funnel me-1"></i>筛选
                            </button>
                        </div>
                    </div>
                </div>

               

                <!-- 用户列表 -->
                <div class="content-card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">用户列表</h5>
                        <div class="d-flex align-items-center">
                            <span class="text-muted me-3">共 {{ pagination.total }} 个用户</span>
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-outline-secondary active" title="列表视图">
                                    <i class="bi bi-list"></i>
                                </button>
                                <button class="btn btn-outline-secondary" title="卡片视图">
                                    <i class="bi bi-grid"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th>
                                            <input type="checkbox" class="form-check-input" id="selectAll">
                                        </th>
                                        <th>用户信息</th>
                                        <th>联系方式</th>
                                        <th>会员类型</th>
                                        <th>注册时间</th>
                                        <th>最后活跃</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for user in users %}
                                    <tr>
                                        <td>
                                            <input type="checkbox" class="form-check-input user-checkbox" value="{{ user.id }}">
                                        </td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="user-avatar me-3">
                                                    <img src="{{ url_for('static', filename='images/default-avatar-40.svg') }}" alt="头像" class="rounded-circle">
                                                </div>
                                                <div>
                                                    <div class="fw-bold">{{ user.username }}</div>
                                                    <small class="text-muted">ID: {{ user.id }}</small>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <div>{{ user.email }}</div>
                                            <small class="text-muted">{{ user.phone or '未绑定' }}</small>
                                        </td>
                                        <td>
                                            {% if user.membership %}
                                                {% if user.membership.plan_type == 'basic' %}
                                                    <span class="badge bg-secondary">基础会员</span>
                                                {% elif user.membership.plan_type == 'premium' %}
                                                    <span class="badge bg-primary">高级会员</span>
                                                {% elif user.membership.plan_type == 'vip' %}
                                                    <span class="badge bg-warning">VIP会员</span>
                                                {% endif %}
                                            {% else %}
                                                <span class="badge bg-light text-dark">未设置</span>
                                            {% endif %}
                                        </td>
                                        <td>{{ user.created_at.strftime('%Y-%m-%d') if user.created_at else '-' }}</td>
                                        <td>
                                            {% if user.last_login_at %}
                                                <span class="text-success">{{ user.last_login_at.strftime('%m-%d %H:%M') }}</span>
                                            {% else %}
                                                <span class="text-muted">从未登录</span>
                                            {% endif %}
                                        </td>
                                        <td>
                                            {% if user.is_active %}
                                                {% if user.is_verified %}
                                                    <span class="badge bg-success">正常</span>
                                                {% else %}
                                                    <span class="badge bg-warning">待激活</span>
                                                {% endif %}
                                            {% else %}
                                                <span class="badge bg-danger">已禁用</span>
                                            {% endif %}
                                        </td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <button class="btn btn-outline-primary" title="查看详情" onclick="viewUserDetail({{ user.id }})">
                                                    <i class="bi bi-eye"></i>
                                                </button>
                                                <button class="btn btn-outline-warning" title="编辑" onclick="editUser({{ user.id }})">
                                                    <i class="bi bi-pencil"></i>
                                                </button>
                                                <div class="btn-group btn-group-sm">
                                                    <button class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">
                                                        <i class="bi bi-three-dots"></i>
                                                    </button>
                                                    <ul class="dropdown-menu">
                                                        <li><a class="dropdown-item" href="#" onclick="resetPassword({{ user.id }})"><i class="bi bi-key me-2"></i>重置密码</a></li>
                                                        {% if user.is_active %}
                                                            <li><a class="dropdown-item" href="#" onclick="toggleUserStatus({{ user.id }}, false)"><i class="bi bi-ban me-2"></i>禁用账户</a></li>
                                                        {% else %}
                                                            <li><a class="dropdown-item" href="#" onclick="toggleUserStatus({{ user.id }}, true)"><i class="bi bi-check-circle me-2"></i>启用账户</a></li>
                                                        {% endif %}
                                                        <li><hr class="dropdown-divider"></li>
                                                        <li><a class="dropdown-item text-danger" href="#" onclick="deleteUser({{ user.id }})"><i class="bi bi-trash me-2"></i>删除用户</a></li>
                                                    </ul>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                    <!-- 分页 -->
                    {% if pagination.pages > 1 %}
                    <div class="card-footer">
                        <nav aria-label="用户列表分页">
                            <ul class="pagination justify-content-center mb-0">
                                {% if pagination.has_prev %}
                                    <li class="page-item">
                                        <a class="page-link" href="{{ url_for('main.admin_users', page=pagination.prev_num) }}">上一页</a>
                                    </li>
                                {% endif %}
                                
                                {% for page_num in pagination.iter_pages() %}
                                    {% if page_num %}
                                        {% if page_num != pagination.page %}
                                            <li class="page-item">
                                                <a class="page-link" href="{{ url_for('main.admin_users', page=page_num) }}">{{ page_num }}</a>
                                            </li>
                                        {% else %}
                                            <li class="page-item active">
                                                <span class="page-link">{{ page_num }}</span>
                                            </li>
                                        {% endif %}
                                    {% else %}
                                        <li class="page-item disabled">
                                            <span class="page-link">…</span>
                                        </li>
                                    {% endif %}
                                {% endfor %}
                                
                                {% if pagination.has_next %}
                                    <li class="page-item">
                                        <a class="page-link" href="{{ url_for('main.admin_users', page=pagination.next_num) }}">下一页</a>
                                    </li>
                                {% endif %}
                            </ul>
                        </nav>
                    </div>
                    {% endif %}
                </div>
            </div>

<!-- 添加用户模态框 - 重新设计 -->
<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="addUserModalLabel">
                    <i class="bi bi-person-plus me-2"></i>添加新用户
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- 错误提示区域 -->
                <div id="errorAlert" class="alert alert-danger d-none">
                    <i class="bi bi-exclamation-triangle me-2"></i>
                    <strong>请修正以下错误：</strong>
                    <ul id="errorList" class="mb-0 mt-2"></ul>
                </div>
                
                <!-- 成功提示区域 -->
                <div id="successAlert" class="alert alert-success d-none">
                    <i class="bi bi-check-circle me-2"></i>
                    <span id="successMessage"></span>
                </div>
                
                <form id="addUserForm" novalidate>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="username" class="form-label">
                                    用户名 <span class="text-danger">*</span>
                                </label>
                                <input type="text" class="form-control" id="username" name="username" 
                                       placeholder="请输入用户名" maxlength="80" required>
                                <div class="form-text">用户名用于登录，支持中文、英文、数字和下划线</div>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="email" class="form-label">
                                    邮箱地址 <span class="text-danger">*</span>
                                </label>
                                <input type="email" class="form-control" id="email" name="email" 
                                       placeholder="请输入邮箱地址" maxlength="120" required>
                                <div class="form-text">用于接收系统通知和密码重置</div>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="phone" class="form-label">手机号码</label>
                                <input type="tel" class="form-control" id="phone" name="phone" 
                                       placeholder="请输入手机号码" maxlength="20">
                                <div class="form-text">可选，用于联系用户</div>
                                <div class="invalid-feedback"></div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">账户状态</label>
                                <div class="form-check mt-2">
                                    <input class="form-check-input" type="checkbox" id="is_active" 
                                           name="is_active" checked>
                                    <label class="form-check-label" for="is_active">
                                        <i class="bi bi-person-check me-1"></i>启用账户
                                    </label>
                                    <div class="form-text">取消勾选将创建禁用状态的账户</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 提示信息 -->
                    <div class="row">
                        <div class="col-12">
                            <div class="alert alert-info border-0">
                                <i class="bi bi-info-circle me-2"></i>
                                <strong>密码设置：</strong>新用户的初始密码将自动设置为 <code>123456</code>，
                                建议用户首次登录后立即修改密码。
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="bi bi-x-circle me-1"></i>取消
                </button>
                <button type="button" class="btn btn-primary" id="submitBtn">
                    <i class="bi bi-check-circle me-1"></i>创建用户
                </button>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<!-- 引入jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
$(document).ready(function() {
    // 用户操作函数
    window.viewUserDetail = function(userId) {
        // TODO: 实现查看用户详情功能
        console.log('查看用户详情:', userId);
        alert('查看用户详情功能待实现');
    };
    
    window.editUser = function(userId) {
        // TODO: 实现编辑用户功能
        console.log('编辑用户:', userId);
        alert('编辑用户功能待实现');
    };
    
    window.resetPassword = function(userId) {
        // TODO: 实现重置密码功能
        console.log('重置密码:', userId);
        if (confirm('确定要重置该用户的密码吗？')) {
            alert('重置密码功能待实现');
        }
    };
    
    window.toggleUserStatus = function(userId, status) {
        // TODO: 实现切换用户状态功能
        console.log('切换用户状态:', userId, status);
        const action = status ? '启用' : '禁用';
        if (confirm(`确定要${action}该用户吗？`)) {
            alert(`${action}用户功能待实现`);
        }
    };
    
    window.deleteUser = function(userId) {
        // TODO: 实现删除用户功能
        console.log('删除用户:', userId);
        if (confirm('确定要删除该用户吗？此操作不可恢复！')) {
            alert('删除用户功能待实现');
        }
    };
    
    // 筛选功能
    window.applyFilters = function() {
        // TODO: 实现筛选功能
        console.log('应用筛选');
        alert('筛选功能待实现');
    };
    
    // 表单验证规则
    const validationRules = {
        username: {
            required: true,
            minLength: 3,
            maxLength: 80,
            pattern: /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
            message: '用户名只能包含字母、数字、下划线和中文，长度3-80个字符'
        },
        email: {
            required: true,
            maxLength: 120,
            pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
            message: '请输入正确的邮箱格式'
        },
        phone: {
            required: false,
            maxLength: 20,
            pattern: /^1[3-9]\d{9}$|^\+\d{1,3}[\s-]?\d{1,14}$/,
            message: '请输入正确的手机号格式'
        }
    };
    
    // 清除错误提示
    function clearErrors() {
        $('#errorAlert').addClass('d-none');
        $('#successAlert').addClass('d-none');
        $('#errorList').empty();
        $('.form-control').removeClass('is-invalid is-valid');
        $('.invalid-feedback').text('');
    }
    
    // 显示错误提示
    function showErrors(errors) {
        clearErrors();
        if (errors && errors.length > 0) {
            const errorList = $('#errorList');
            errors.forEach(error => {
                errorList.append(`<li>${error}</li>`);
            });
            $('#errorAlert').removeClass('d-none');
            // 滚动到错误提示
            $('#errorAlert')[0].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
    }
    
    // 显示成功提示
    function showSuccess(message) {
        clearErrors();
        $('#successMessage').text(message);
        $('#successAlert').removeClass('d-none');
    }
    
    // 字段验证
    function validateField(fieldName, value) {
        const rule = validationRules[fieldName];
        const field = $(`#${fieldName}`);
        const errors = [];
        
        if (rule.required && !value.trim()) {
            errors.push(`${field.prev('label').text().replace(' *', '')}不能为空`);
        } else if (value.trim()) {
            if (rule.minLength && value.length < rule.minLength) {
                errors.push(`${field.prev('label').text().replace(' *', '')}长度不能少于${rule.minLength}个字符`);
            }
            if (rule.maxLength && value.length > rule.maxLength) {
                errors.push(`${field.prev('label').text().replace(' *', '')}长度不能超过${rule.maxLength}个字符`);
            }
            if (rule.pattern && !rule.pattern.test(value)) {
                errors.push(rule.message);
            }
        }
        
        // 更新字段样式
        if (errors.length > 0) {
            field.removeClass('is-valid').addClass('is-invalid');
            field.siblings('.invalid-feedback').text(errors[0]);
        } else if (value.trim() || rule.required) {
            field.removeClass('is-invalid').addClass('is-valid');
            field.siblings('.invalid-feedback').text('');
        }
        
        return errors;
    }
    
    // 实时验证
    $('#username, #email, #phone').on('blur', function() {
        const fieldName = $(this).attr('name');
        const value = $(this).val();
        validateField(fieldName, value);
    });
    
    // 提交表单
    $('#submitBtn').on('click', function() {
        const $btn = $(this);
        const originalText = $btn.html();
        
        // 收集表单数据
        const formData = {
            username: $('#username').val().trim(),
            email: $('#email').val().trim(),
            phone: $('#phone').val().trim(),
            is_active: $('#is_active').is(':checked')
        };
        
        // 验证所有字段
        let allErrors = [];
        Object.keys(validationRules).forEach(fieldName => {
            const errors = validateField(fieldName, formData[fieldName] || '');
            allErrors = allErrors.concat(errors);
        });
        
        if (allErrors.length > 0) {
            showErrors(allErrors);
            return;
        }
        
        // 如果手机号为空，不发送该字段
        if (!formData.phone) {
            delete formData.phone;
        }
        
        // 显示加载状态
        $btn.prop('disabled', true)
            .html('<i class="bi bi-hourglass-split me-1"></i>创建中...');
        
        // 发送请求
        $.ajax({
            url: '/api/admin/users',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
            },
            data: JSON.stringify(formData),
            success: function(response) {
                if (response.success) {
                    showSuccess(response.message);
                    // 重置表单
                    $('#addUserForm')[0].reset();
                    $('.form-control').removeClass('is-invalid is-valid');
                    $('#is_active').prop('checked', true);
                    
                    // 2秒后关闭模态框并刷新页面
                    setTimeout(() => {
                        $('#addUserModal').modal('hide');
                        location.reload();
                    }, 2000);
                } else {
                    showErrors(response.errors || [response.message]);
                }
            },
            // 在AJAX error回调中添加更详细的错误信息
            error: function(xhr, status, error) {
                console.error('请求失败:', {
                    status: xhr.status,
                    statusText: xhr.statusText,
                    responseText: xhr.responseText,
                    error: error
                });
                
                let errorMessage = '网络错误，请稍后重试';
                
                if (xhr.status === 0) {
                    errorMessage = '无法连接到服务器，请检查网络连接或确认服务器是否启动';
                } else if (xhr.status === 404) {
                    errorMessage = 'API接口不存在，请检查URL路径';
                } else if (xhr.status === 422) {
                    // 422 是数据验证错误，尝试解析详细错误信息
                    try {
                        const response = JSON.parse(xhr.responseText);
                        if (response.data && Array.isArray(response.data)) {
                            showErrors(response.data);
                            return;
                        } else if (response.message) {
                            errorMessage = response.message;
                        }
                    } catch (e) {
                        errorMessage = '数据验证失败，请检查输入信息';
                    }
                } else if (xhr.status === 500) {
                    errorMessage = '服务器内部错误，请查看服务器日志';
                } else if (xhr.responseJSON) {
                    if (xhr.responseJSON.errors) {
                        showErrors(xhr.responseJSON.errors);
                        return;
                    } else if (xhr.responseJSON.message) {
                        errorMessage = xhr.responseJSON.message;
                    }
                }
                
                showErrors([errorMessage]);
            },
            complete: function() {
                // 恢复按钮状态
                $btn.prop('disabled', false).html(originalText);
            }
        });
    });
    
    // 模态框关闭时清除表单
    $('#addUserModal').on('hidden.bs.modal', function() {
        $('#addUserForm')[0].reset();
        clearErrors();
        $('.form-control').removeClass('is-invalid is-valid');
        $('#is_active').prop('checked', true);
    });
    
    // 其他现有功能保持不变...
    // ... 保留原有的筛选、搜索等功能
});
</script>
{% endblock %}